<?php

namespace common\web;

use Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use common\helpers\DateHelper;
use common\helpers\Url;

/**
 * AuthentStsAction represents an action that displays a view according to a user-specified parameter.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AuthentStsAction extends Action {

    /**
     * Displays a model.
     * @param string $id the primary key of the model.
     * @return \yii\db\ActiveRecordInterface the model being displayed
     */
    public function run() {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $oss = Yii::$app->alioss;
        $authdata = $oss->getStsAuthData();

        $id = ArrayHelper::getValue($authdata, 'AccessKeyId');
        $key = ArrayHelper::getValue($authdata, 'AccessKeySecret');
        $securityToken = ArrayHelper::getValue($authdata, 'SecurityToken');

        // $host的格式为 bucketname.endpoint，请替换为您的真实信息。
        $host = $oss->host;
        // $callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实URL信息。
        $callbackUrl = Url::to('@web/xhr/oss/listen', true);
        // 用户上传文件时指定的路径
        $dir = 'attachments/sts/' . date('Ym/d') . '/';

        $callback_param = [
            'callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType' => "application/x-www-form-urlencoded"
        ];
        $callback_string = Json::encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = DateHelper::gmtToISO8601($end);
        $conditions = [
            //最大文件大小.用户可以自己设置
            [
                0 => 'content-length-range',
                1 => 0,
                2 => 1048576000,
            ],
            // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
            [
                0 => 'starts-with',
                1 => '$key',
                2 => $dir
            ]
        ];
        $policy = Json::encode([
            'expiration' => $expiration,
            'conditions' => $conditions
        ]);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        return [
            'accessid' => $id,
            'host' => $host,
            'token' => $securityToken,
            'policy' => $base64_policy,
            'signature' => $signature,
            'expire' => $end,
            'callbackUrl' => $callbackUrl,
            'callback' => $base64_callback_body,
            'dir' => $dir, // 这个参数是设置用户上传文件时指定的前缀。
        ];
    }

}
